<?php

namespace App\Admin\Controllers\Stat;

use App\Http\Controllers\Controller;
use App\Model\Stat\StatDailyKeep;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;

class StatDailyKeepController extends Controller
{
    use ModelForm;

    public $keepDays = [1, 2, 3, 7, 15, 30];

    public function index()
    {
        $content = new Content();
        $content->header('留存日报');
        $content->description('当天新注册，第N天活跃留存');
        $content->body($this->grid());
        return $content;
    }

    protected function grid()
    {
        $grid = new Grid(new StatDailyKeep());
        $grid->model()->orderBy('dt', 'desc');
        $grid->dt('日期')->sortable();
        $grid->stat_type('用户类型')->display(function ($data) {
            return StatDailyKeep::STAT_TYPE[$data] ?? "-";
        });
        foreach ($this->keepDays as $day) {
            $field = "keep_{$day}";
            $fieldNum = "keep_{$day}_num";
            $grid->{$field}("{$day}日留存")->display(function ($data) use ($field, $fieldNum) {
                return "{$data} % (" . $this->{$fieldNum} . ")";
            })->sortable();
        }
        $grid->disableExport();
        $grid->disableRowSelector();
        $grid->disableActions();
        $grid->disableCreateButton();
        $grid->filter(function ($filter) {
            $filter->expand();
            $filter->disableIdFilter();
            $filter->column(1 / 3, function ($filter) {
                $filter->date('dt', '日期');
            });
            $filter->column(1 / 3, function ($filter) {
                $filter->equal('stat_type', '类型')->select(StatDailyKeep::STAT_TYPE);
            });
        });
        $grid->actions(function (Grid\Displayers\Actions $actions) {
            $actions->disableDelete();
            $actions->disableEdit();
            $actions->disableView();
        });
        return $grid;
    }
}
